import { Component } from '@angular/core';
import * as echarts from 'echarts';
import { WorkbenchService } from 'src/app/@core/mock/datasERVICE/workbench.service';

@Component({
  selector: 'app-Sales-workbench',
  templateUrl: './sales-workbench.component.html',
  styleUrls: ['./sales-workbench.component.scss']
})
export class SalesWorkbenchComponent {
  tabActiveId: string | number = 'tab1';
  activeTabData: any;
  tabItems = [
    {
      id: 'tab1',
      title: '待生产',
    },
    {
      id: 'tab2',
      title: '未完结',
    }
  ]
  amountData: any = {
    "totalSaleOrderAmount": 0,
    "totalSaleDeliveryAmount": 0,
    "monthSaleOrderAmount": 0,
    "monthSaleDeliveryAmount": 0,
    "saleOrderAmountMonthUpRate": 0,
    "saledeliveryAmountMonthUpRate": 0,
    "monthSaleDeliveryRate": 0,
    "monthSaleReturnAmount": 0,
    "salereturnAmountMouthUpRate": 0,
    "monthSaleDeliveryRateUpRate": 0
  }
  todoList: any = {
    "allSaleTasksCount": 0,
    "saleOrdeTasksrCount": 0,
    "saleDeliveryTasksCount": 0,
    "saleReturnTasksCount": 0
  }
  statistics = []
  finishedData = {
    "finishedCount": 0,
    "unfinishedCount": 0
  }
  monthDelivery: any = [
    {
      "month": "",
      "requiredDelivery": 0,
      "delivered": 0,
      "undelivered": 0,
      "deliveredOverdue": 0,
      "undeliveredOverdue": 0
    },
    {
      "month": "",
      "requiredDelivery": 0,
      "delivered": 0,
      "undelivered": 0,
      "deliveredOverdue": 0,
      "undeliveredOverdue": 0
    },
    {
      "month": "",
      "requiredDelivery": 0,
      "delivered": 0,
      "undelivered": 0,
      "deliveredOverdue": 0,
      "undeliveredOverdue": 0
    }
  ]
  returnCount = [
    {
      "month": "",
      "returnCount": 0,
      "returnGrowthRate": 0
    },
    {
      "month": "",
      "returnCount": 0,
      "returnGrowthRate": 0
    },
    {
      "month": "",
      "returnCount": 0,
      "returnGrowthRate": 0
    }
  ]
  constructor(private saleWorkbenchService: WorkbenchService) { }
  ngOnInit() {
    this.saleWorkbenchService.getAmountData().subscribe((res: any) => {
      this.amountData = res;
    });
    this.saleWorkbenchService.getToDoList().subscribe((res: any) => {
      this.todoList = res;
    });
    this.saleWorkbenchService.getStatistics().subscribe((res: any) => {
      this.statistics = res;
      this.saleData();
    });
    // this.saleWorkbenchService.getIsFinished().subscribe((res: any) => {
    //   this.finishedData = res;
    //   this.deliveryData();
    // });
    this.saleWorkbenchService.getRetutnCount().subscribe((res: any) => {
      this.returnCount = res;
      this.renderAfterSalesChart();
    })
    this.saleWorkbenchService.getMonthDelivery().subscribe((res: any) => {
      this.monthDelivery = res;
      this.deliveryData2();
    });
  }
  saleData() {
    const option = {
      tooltip: {
        show: true,
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
        },
        formatter: function (params) {
          let result = params[0].name + '<br/>';
          params.forEach(function (item) {
            result += item.marker + item.seriesName + '：￥' + item.value.toFixed(2) + '<br/>';
          });
          return result;
        }
      },
      grid: {
        left: '5%',
        right: '5%',
        bottom: '5%',
        top: '12%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: this.statistics.map(item => item.month),
      },
      yAxis: {
        type: 'value',
        name: '销售额(元)',
        axisLine: {
          show: true,
        },
        axisLabel: {
          formatter: '￥{value}'
        }
      },
      series: [
        {
          data: this.statistics.map(item => item.monthSaleAmount),
          name: "销售额(元)",
          type: 'line',
          smooth: true,
          label: {
            show: true,
            formatter: function (params: any) {
              return `￥${params.value.toFixed(2)}`;
            }
          },
        }
      ]
    }
    const myChart = echarts.init(document.getElementById('xiaoshoue') as HTMLElement);
    myChart.setOption(option)
    myChart.resize() // 初始化后立即调用 resize 方法
    window.addEventListener('resize', function () {
      myChart.resize()
    })
  }
  // deliveryData() {
  //   const option = {
  //     tooltip: {
  //       trigger: 'axis',
  //       axisPointer: {
  //         type: 'shadow'
  //       }
  //     },
  //     legend: {
  //       data: [ '已交付', '未交付']
  //     },
  //     grid: {
  //       left: '3%',
  //       right: '4%',
  //       bottom: '3%',
  //       containLabel: true
  //     },
  //     xAxis: {
  //       type: 'category',
  //       data: ['已交付', '未交付'],
  //     },
  //     yAxis: {
  //       type: 'value',
  //       name: "数量"
  //     },
  //     series: [
  //       {
  //         type: 'bar',
  //         data: [this.finishedData.finishedCount, this.finishedData.unfinishedCount],
  //         barWidth: '30%',
  //         itemStyle: {
  //           color: function(params) {
  //             const colorList = ['#66bb6a', '#ffa726', ]; // 蓝色系, 橙色系, 绿色系
  //             return colorList[params.dataIndex];
  //           }
  //         }
  //       },

  //     ]
  //   }
  //   const myChart = echarts.init(document.getElementById('jiaofu') as HTMLElement);
  //   myChart.setOption(option);
  //   myChart.resize(); // 初始化后立即调用 resize 方法
  //   window.addEventListener('resize', function () {
  //     myChart.resize();
  //   });
  // }
  deliveryData2() {
    const currentMonth = new Date().getMonth(); // 获取当前月份（0-11，0表示1月，11表示12月）
    // 计算要保留的起始索引和结束索引
    const startIndex = currentMonth - 2 >= 0 ? currentMonth - 2 : 0;
    const endIndex = currentMonth + 1; // slice 方法的结束索引是非包含的
    // 保留当前月份及其前两个月的数据
    this.monthDelivery = this.monthDelivery.slice(startIndex, endIndex);
    const dates = this.monthDelivery.map(item => item.month);
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['需交付', '已交付', '未交付', '已交付(逾期)', '未交付(逾期)'],
        top: '0%',
        left: "16%",
      },
      grid: {
        left: '0%',
        right: '0%',
        bottom: '0%',
        top: '30%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: dates,
        name: "月份"
      },
      yAxis: {
        type: 'value',
        name: "单据数量"
      },
      series: [
        {
          name: '需交付',
          type: 'bar',
          data: this.monthDelivery.map(item => item.requiredDelivery),
          itemStyle: {
            color: '#5470C6' // 设置颜色
          }
        },
        {
          name: '已交付',
          type: 'bar',
          data: this.monthDelivery.map(item => item.delivered),
          itemStyle: {
            color: '#91CC75' // 设置颜色
          }
        },
        {
          name: '未交付',
          type: 'bar',
          data: this.monthDelivery.map(item => item.undelivered),
          itemStyle: {
            color: '#FAC858' // 设置颜色
          }
        },
        {
          name: '已交付(逾期)',
          type: 'bar',
          data: this.monthDelivery.map(item => item.deliveredOverdue),
          itemStyle: {
            color: '#73C0DE' // 设置颜色
          }
        },
        {
          name: '未交付(逾期)',
          type: 'bar',
          data: this.monthDelivery.map(item => item.undeliveredOverdue),
          itemStyle: {
            color: '#EE6666' // 设置颜色
          }
        }
      ]
    }
    const myChart = echarts.init(document.getElementById('jiaofu') as HTMLElement);
    myChart.setOption(option);
    myChart.resize(); // 初始化后立即调用 resize 方法
    window.addEventListener('resize', function () {
      myChart.resize();
    });
  }
  renderAfterSalesChart() {
    const currentMonth = new Date().getMonth(); // 获取当前月份（0-11，0表示1月，11表示12月）
    // 计算要保留的起始索引和结束索引
    const startIndex = currentMonth - 2 >= 0 ? currentMonth - 2 : 0;
    const endIndex = currentMonth + 1; // slice 方法的结束索引是非包含的
    // 保留当前月份及其前两个月的数据
    this.returnCount = this.returnCount.slice(startIndex, endIndex);
    const months = this.returnCount.map(item => item.month);
    const returnData = this.returnCount.map(item => item.returnCount);
    const growthRateData = this.returnCount.map(item => item.returnGrowthRate);
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['退货金额', '增长率']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: months
      },
      yAxis: [
        {
          type: 'value',
          name: '退货金额',
          position: 'left'
        },
        {
          type: 'value',
          name: '增长率%',
          position: 'right',
          axisLabel: {
            formatter: '{value} %'
          }
        }
      ],
      series: [
        {
          name: '退货金额￥',
          type: 'bar',
          data: returnData,
        },
        {
          name: '增长率%',
          type: 'line',
          yAxisIndex: 1,
          color: "#ff4a4f",
          data: growthRateData
        }
      ]
    };
    const myChart = echarts.init(document.getElementById('afterSalesChart') as HTMLElement);
    myChart.setOption(option);
    myChart.resize(); // 初始化后立即调用 resize 方法
    window.addEventListener('resize', function () {
      myChart.resize();
    });
  }
}
